from rest_framework.viewsets import ModelViewSet
from rest_framework.generics import ListAPIView
from rest_framework.response import Response
from rest_framework import status

from fdfs_client.client import Fdfs_client

from apps.goods.models import SKUImage
from apps.goods.models import SKU
from apps.meiduo_admin.utils import PageNum
from apps.meiduo_admin.serializers.image import ImageSeriazlier, SKUSerializer


class ImageView(ModelViewSet):

    # 图片查询集
    queryset = SKUImage.objects.all().order_by('id')
    # 指定序列化器
    serializer_class = ImageSeriazlier
    # 分页器
    pagination_class = PageNum

    # 要将图片上传到FastDFS，所以需要重写create方法
    def create(self, request, *args, **kwargs):
        # 1.接受参数(前端提交的图片image)
        data = request.FILES.get('image')
        # 2.创建FastDFS客户端
        client = Fdfs_client('utils/fastdfs/client.conf')
        # 3.上传二进制图片到FastDFS
        result = client.upload_by_buffer(data.read())
        # 4.判断是否上传成功
        """
        'Remote file_id' (140089296510000) = {str} 'group1/M00/00/02/wKgrVV5Ivl6ALZbuAAEYrO0lPdw2086520'
        'Group name' (140089296509936) = {str} 'group1'
        'Status' (140089310908744) = {str} 'Upload successed.'
        'Uploaded size' (140089296510128) = {str} '70.00KB'
        'Storage IP' (140089296510192) = {str} '192.168.43.85'
        'Local file name' (140089296510064) = {str} ''
        """
        if result['Status'] != 'Upload successed.':
            # 不成功，返回403禁止访问
            return Response(status=status.HTTP_403_FORBIDDEN)
        # 5.成功后获取图片id和地址
        image_url = result['Remote file_id']
        sku_id = request.data.get('sku')
        # 6.保存对象到数据库
        img = SKUImage.objects.create(sku_id=sku_id, image=image_url)
        # 7.响应给前端结果
        return Response(
            {
                'id': 'img.id',
                'sku': 'sku_id',
                'image': 'img.image.url'
            },
            status=201  # 必须响应201状态码，因为前端会根据201判断
        )


class SKUView(ListAPIView):

    # sku查询集
    queryset = SKU.objects.all()
    # 指定序列化器
    serializer_class = SKUSerializer